/**
 * Copyright 2009 Takahiko Ito
 * 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0 
 *        
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.unigram.oluolu.extractor;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.conf.Configuration;
import org.unigram.oluolu.common.OluoluConstants;
import org.unigram.oluolu.common.OluoluException;
import org.unigram.oluolu.common.Query;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * BasicExtractor. 
 */
public class BasicExtractor 
    implements IExtractor {
    
    /** Date data format. */
    private SimpleDateFormat sdf;

    /**
     * Default Constructor.
     */
    public BasicExtractor() {
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * Constructor.
     * @param conf configuration instance
     */
    public BasicExtractor(final Configuration conf) {
        String dateFormat = conf.get(OluoluConstants.DATE_FORMAT,
                OluoluConstants.DEFAULT_DATE_FORMAT);
        sdf = new SimpleDateFormat(dateFormat);
    }

    /**
     * Return a Query object extracted from input string.
     * 
     * @param inputStr input string which contains time,
     *          userId and query string.
     * @throws OluoluException -
     * @return Query instance extracted from inputStr
     */
    public final Query extract(final String inputStr)
    throws OluoluException {
        String[] tokens = inputStr.split("\t");

        if (tokens.length < 3) {
            throw new OluoluException(
                    "Input shoud have more than three segments: " + inputStr);
        }
        String userId = tokens[0];
        String queryStr = tokens[1];

        Date date = new Date();
        try {
            date = sdf.parse(tokens[2]);
        } catch (ParseException e) {
            throw new OluoluException(e);
        }
        return new Query(new Text(userId), new Text(queryStr),
                new LongWritable(date.getTime()));
    }
}
